package httpx

import (
	"ci-control-backend/tools"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/pkg/errors"
	"reflect"
)

// Query 解析单个参数
func (c *Context) Query(key string, dst any) (err error) {
	if dst == nil {
		return errors.New("dst不能为空指针")
	}
	str := c.Context.Query(key)
	switch v := dst.(type) {
	case *string:
		*v = str
		break
	case *int:
		*v, err = tools.ParseInt(str)
		break
	case *uint:
		*v, err = tools.ParseUint(str)
		break
	case *int64:
		*v, err = tools.ParseInt64(str)
		break
	case *uint64:
		*v, err = tools.ParseUint64(str)
		break
	default:
		err = errors.New(fmt.Sprintf("dst是不支持的类型：%v", reflect.TypeOf(dst)))
	}
	return err
}

// MultiQuery 解析多个query参数
func (c *Context) MultiQuery(args gin.H) (err error) {
	for key, dst := range args {
		err = c.Query(key, dst)
		if err != nil {
			break
		}
	}
	return err
}

func (c *Context) ParamInt(key string) int {
	str := c.Context.Param(key)
	v, _ := tools.ParseInt(str)
	return v
}

func (c *Context) ParamUint(key string) uint {
	str := c.Context.Param(key)
	v, _ := tools.ParseUint(str)
	return v
}
